package com.JZ.QM.controller;

import com.JZ.QM.common.entity.UserAccountEntity;
import com.JZ.QM.common.entity.UserInfoEntity;
import com.JZ.QM.common.utils.CommonResult;
import com.JZ.QM.dto.RealNameAuthenticationDTO;
import com.JZ.QM.service.UserAccountService;
import com.JZ.QM.service.UserInfoService;
import com.JZ.QM.utils.RealNameAuthentication;
import com.JZ.QM.utils.RiskLevel;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cyc
 * @email cyc@gmail.com
 * @date 2020/6/24 11:37
 */
@RestController
@RefreshScope
@Slf4j
@RequestMapping(value="/userInfo")
public class UserInfoController {

    @Resource
    UserInfoService userInfoService;
    @Resource
    UserAccountService userAccountService;

    /**
     * 根据用户身份证号，姓名，手机号，住址对用户进行实名认证,并实现开户
     * @param realNameAuthenticationDTO:实名认证数据传输对象包括（用户身份证号，姓名，手机号，住址）信息
     * @return
     * @throws Exception
     */
    @Transactional
    @PostMapping("/realNameAuthentication")
    public CommonResult realNameAuthentication(@Valid @RequestBody RealNameAuthenticationDTO realNameAuthenticationDTO) throws Exception {
        //用户基本信息对象
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        boolean realNameAuthenticationState = false;
        boolean openUserAccountState = false;
        //身份校验的返回集
        HashMap authenticationReault;

        //根据id获取用户的基本信息
        userInfoEntity=userInfoService.getById(realNameAuthenticationDTO.getUserId());
        //判断用户是否存在
        if (userInfoEntity == null){
            return CommonResult.error(201,"用户的用户id不存在");
        } else {
            //判断是否已经实名认证
            if(userInfoEntity.getUserName() !=null && userInfoEntity.getUserName().length()>0){
                return CommonResult.error(201,"该用户已经进行实名认证，信息无法更改");
            } else {
                //进行身份证号与用户姓名的身份验证
//            authenticationReault= RealNameAuthentication.getResult(
//                    realNameAuthenticationDTO.getUserCard(),
//                    realNameAuthenticationDTO.getUserName());
                //开启实名认证 Boolean.valueOf((authenticationReault.get("state").toString())).booleanValue()
                if (true){
                    //更新用户的身份信息
                    realNameAuthenticationState=userInfoService.realNameAuthentication(realNameAuthenticationDTO);
                    openUserAccountState=userAccountService.openUserAccount(realNameAuthenticationDTO.getUserId(),realNameAuthenticationDTO.getUserPassword());
                    //判断时候已经更新信息
                    if (realNameAuthenticationState && openUserAccountState){
                        return CommonResult.success();
                    } else {
                        return CommonResult.error(201,"用户身份信息更新失败");
                    }
                } else {
                    return CommonResult.error(201,authenticationReault.get("description").toString());
                }
            }

        }
    }

    /**
     * 根据用户id与测评结果集，返回用户的风险类型并更新风险类型
     * @param userId：用户的iD
     * @param riskResult:用户风险测评的测评结果
     * @return
     */
    @RequestMapping("/calculateRiskLevel")
    public CommonResult calculateRiskLevel(Long userId,String riskResult) throws JSONException {
        //风险测评的分数
        int scoreResult=0;
        //定义json数据
        JSONObject json=new JSONObject();
        //json数据的item
        JSONObject jsonItem=new JSONObject();

        int riskLevel=-1;
        //用户的更新状态
        boolean updateState=false;
        //用户的基本信息
        UserInfoEntity userInfoEntity=new UserInfoEntity();

        if (riskResult == null || (riskResult != null && riskResult.length() != 10) ){
            return CommonResult.error(201,"题目的数量不符");
        }
        //根据用户id获取用户的基本信息
        userInfoEntity=userInfoService.getById(userId);
        if (userInfoEntity == null){
            return CommonResult.error(201,"用户id错误，此用户不存在");
        } else {
            //获取风险等级json
            json= RiskLevel.getJson();
            for (int i=0;i<10;i++){
                //获取每个题目对应的选项的分值
                jsonItem= (JSONObject) json.get(String.valueOf(i));
                scoreResult+=Integer.parseInt(jsonItem.get(String.valueOf(riskResult.charAt(i))).toString());
            }
            //获取对应的风险等级
            riskLevel=RiskLevel.getRiskLevel(scoreResult);
            //更新用户的风险等级
            updateState=userInfoService.updateRiskLevel(userId,String.valueOf(riskLevel));
            if (updateState == true){
                //返回风险等级及其描述
                return getRiskLevel(userId);
            } else {
                return CommonResult.error(201,"风险等级信息更新失败");
            }
        }
    }

    /**
     * 获取风险等级及其描述
     * @param userId
     * @return
     */
    @RequestMapping("/getRiskLevel")
    public CommonResult getRiskLevel(Long userId) throws JSONException {
        //用户实体类
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        //风险等级及其描述
        Map<String,String> riskInfoMap = new HashMap<>();

        userInfoEntity = userInfoService.getById(userId);

        if (userInfoEntity != null ){
            //判断是否进行了风险测评
            if(userInfoEntity.getUserRisk() != null){

                riskInfoMap = userInfoService.getRiskLevelInfo(Integer.valueOf(userInfoEntity.getUserRisk()));

                return CommonResult.success()
                        .put("riskLevel",riskInfoMap.get("riskLevel"))
                        .put("info",riskInfoMap.get("info"))
                        .put("riskNum",userInfoEntity.getUserRisk());
            }else{
                return CommonResult.error(201,"该用户还未进行风险测评");
            }
        }else {
            return CommonResult.error(201,"账号不存在");
        }
    }
    /**
     * 获取实名信息
     * @param userId
     * @return
     */
    @RequestMapping("/getAuthenticationInfo")
    public CommonResult getAuthenticationInfo(Long userId){
        //用户实体类
        UserInfoEntity userInfoEntity = new UserInfoEntity();

        userInfoEntity = userInfoService.getById(userId);

        if (userInfoEntity != null){
            return CommonResult.success()
                    .put("userName",userInfoEntity.getUserName())
                    .put("userCard",userInfoEntity.getUserCard())
                    .put("userAddress",userInfoEntity.getUserAddress())
                    .put("userPhone",userInfoEntity.getUserPhone());
        }else {
            return CommonResult.error(201,"账号不存在");
        }
    }

    /**
     * 获取用户的平台账户信息
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/getAccountAmoount")
    public CommonResult showAccountAmoount(Long userId){
        //用户账号信息
        UserAccountEntity userAccountEntity=new UserAccountEntity();

        //获取用户的账号信息
        userAccountEntity=userAccountService.getAccount(userId);
        if(userAccountEntity == null ){
            return CommonResult.error(201,"该用户未开通平台账户");
        } else {
            return CommonResult.success().put("userAccountAmoount",userAccountEntity.getAccountAmoount());
        }
    }

    /**
     * 获取用户的基本信息
     * @param userId
     * @return
     */
    @RequestMapping("/getUserInfo")
    public CommonResult getUserInfo(Long userId){
        //用户的基本信息
        UserInfoEntity userInfoEntity=new UserInfoEntity();

        userInfoEntity=userInfoService.getById(userId);

        return CommonResult.success().put("userInfo",userInfoEntity);
    }



}
